package com.example.sell.service.impl;

import com.example.sell.bean.ProductCategory;
import com.example.sell.common.ResultVOUtil;
import com.example.sell.repository.CategoryRepository;
import com.example.sell.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

/**
 * Created by IntelliJ IDEA.
 *
 * @author ouyangzhixiang
 * @date 2018/6/28
 */
@Service
public class CategoryServiceImpl implements CategoryService {
    @Autowired
    private CategoryRepository categoryRepository;

    /**
     * 查找单个商品商品类目
     *
     * @param categoryId 类目id
     * @return
     */
    @Override
    public ResultVOUtil<Optional<ProductCategory>> findOne(Integer categoryId) {
        Optional<ProductCategory> productCategory = categoryRepository.findById(categoryId);
        if (productCategory.isPresent()) {
            return ResultVOUtil.createBySuccess(productCategory);
        }
        return ResultVOUtil.createByErrorMessage("该类信息不存在");
    }

    @Override
    public List<ProductCategory> findAll() {
        return categoryRepository.findAll();
    }

    /**
     * 添加/更新商品类目
     * @param productCategory
     * @return
     */
    @Override
    public ResultVOUtil<ProductCategory> save(ProductCategory productCategory) {
        //如果未获取到类目Id则代表增加类目
        ProductCategory addCategory = new ProductCategory();
        if (productCategory.getCategoryId() != null) {
            addCategory=categoryRepository.findById(productCategory.getCategoryId()).get();
        }
        addCategory.setCategoryType(productCategory.getCategoryType());
        addCategory.setCategoryName(productCategory.getCategoryName());
        addCategory=categoryRepository.save(addCategory);
        return ResultVOUtil.createBySuccess(addCategory);
    }

    @Override
    public List<ProductCategory> findByCategoryTypeIn(List<Integer> categoryType) {
        return categoryRepository.findByCategoryTypeIn(categoryType);
    }
}
